import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { getStatus } from '@/api/user'
import store from '../store/index'
import Home from '../views/Home.vue'
import Personal from '../views/personal/Personal.vue'
import Calendar from '../views/Calendar.vue'
import Wallet from '../views/Wallet.vue'
import Chart from '../views/Chart.vue'
import Bookkeeping from '../views/bill/Bookkeeping.vue'
import SetBudget from '../views/budget/SetBudget.vue'
import BookManage from '../views/book/BookManage.vue'
import BillDetail from '../views/bill/BillDetail.vue'
import NewBook from '../views/book/NewBook.vue'
import SearchBill from '../views/bill/SearchBill.vue'
import NewClass from '../views/class/NewClass.vue'
import EditClass from '../views/class/EditClass.vue'
import Account from '../views/personal/Account.vue'
import BillList from '../views/bill/BillList.vue'
import Test from '../views/Test.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
   {
    path: '/calendar',
    name: 'Calendar',
    component: Calendar
  }, {
    path: '/wallet',
    name: 'Wallet',
    component: Wallet
  }, {
    path: '/chart',
    name: 'Chart',
    component: Chart
  }, {
    path: '/personal',
    name: 'Personal',
    component: Personal
  }, 
  {
    path: '/bookkeeping',
    name: 'Bookkeeping',
    component: Bookkeeping
  }, {
    path: '/setBudget',
    name: 'SetBudget',
    component: SetBudget
  }, {
    path: '/bookManage',
    name: 'BookManage',
    component: BookManage
  }, {
    path: '/billDetail',
    name: 'BillDetail',
    component: BillDetail
  }, {
    path: '/newBook',
    name: 'NewBook',
    component: NewBook
  }, {
    path: '/searchBill',
    name: 'SearchBill',
    component: SearchBill
  }, {
    path: '/newClass',
    name: 'NewClass',
    component: NewClass
  }, {
    path: '/editClass',
    name: 'EditClass',
    component: EditClass
  }, {
    path: '/account',
    name: 'Account',
    component: Account
  }, {
    path: '/billList',
    name: 'BillList',
    component: BillList
  }, {
    path: '/test',
    name: 'Test',
    component: Test
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// to：要到哪里去，from：从哪里来，next：路由的控制参数
router.beforeEach((to, from, next) => {
  getStatus().then((res) => {
    if(typeof res.code === 'number' && res.code === 100) {
      store.commit('get_user_info', res.data.user)
      if(store.state.user) {
        store.state.isLogin = true
      } else {
        store.state.isLogin = true
      }
    } else {
      store.state.isLogin = true
    }
  })
  if(to.path === '/login') {
    next()
    return
  }
  if(to.path === '/') {
    next()
    return
  }
  next()
})

export default router
